package com.example.webdemo.service.impl;

import com.example.webdemo.dao.ArticleMapper;
import com.example.webdemo.dao.HomeArticleMapper;
import com.example.webdemo.dao.HomeGridMapper;
import com.example.webdemo.model.Article;
import com.example.webdemo.model.HomeArticle;
import com.example.webdemo.model.Tag;
import com.example.webdemo.service.ArticleService;
import com.example.webdemo.service.HomeArticleService;
import com.example.webdemo.service.TagsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author zp
 * @version 1.0
 * @description: HomeArticleServiceImpl
 * @date 2023/7/31 19:13
 */
@Service
public class HomeArticleServiceImpl implements HomeArticleService {
    @Resource
    private HomeArticleMapper homeArticleMapper;
    @Resource
    private TagsService tagsService;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return homeArticleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(HomeArticle record) {
        return homeArticleMapper.insert(record);
    }

    @Override
    public int insertSelective(HomeArticle record) {
        return homeArticleMapper.insertSelective(record);
    }

    @Override
    public HomeArticle selectByPrimaryKey(Integer id) {
        return homeArticleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(HomeArticle record) {
        return homeArticleMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(HomeArticle record) {
        return homeArticleMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<HomeArticle> selectAll() {
        List<HomeArticle> homeArticleList = homeArticleMapper.selectAll();
        if(homeArticleList==null){
            return new ArrayList<>();
        }
        List<Tag> tags = tagsService.selectAll();
        for (HomeArticle homeArticle: homeArticleList) {
            List<Tag> tagList = new ArrayList<>();
            String[] tagIds = homeArticle.getTags().split(",");
            for (String id: tagIds) {
                Integer tagId = Integer.parseInt(id);
                for (Tag tag: tags) {
                    if(tagId.equals(tag.getId())){
                        tagList.add(tag);
                    }
                }
            }
            homeArticle.setTagNames(tagList);
        }
        return homeArticleList;
    }
}
